package com.ocom.common.vo;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpClientUtil {

	private static final Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
	
	/**
	 * 普通的post  json请求方式
	 * @param reqJson		请求的json
	 * @return
	 */
	public static String httpClientPost(String url, String headToken, String reqJson) {
		String result = null;
		// 获得Http客户端
		CloseableHttpClient httpClient = HttpClientBuilder.create().build();

		// 创建Post请求
		HttpPost httpPost = new HttpPost(url);
		
		RequestConfig requestConfig = RequestConfig.
	        		custom().
	        		setConnectTimeout(2000).
	        		setConnectionRequestTimeout(2000).
	        		setSocketTimeout(2000).
	        		build();
		httpPost.setConfig(requestConfig);
		
		if(reqJson !=null){
			StringEntity entity = new StringEntity(reqJson, "UTF-8");
			
			httpPost.setEntity(entity);
		}
		
		httpPost.setHeader("Content-Type", "application/json");
		
		httpPost.setHeader("token", headToken);
		
		// 响应模型
		CloseableHttpResponse response = null;
		try {
			// 由客户端执行(发送)Post请求
			response = httpClient.execute(httpPost);
			// 从响应模型中获取响应实体
			HttpEntity responseEntity = response.getEntity();

			//logger.debug("响应状态为:" + response.getStatusLine());
			if (responseEntity != null) {
				

				result =  EntityUtils.toString(responseEntity);
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				// 释放资源
				if (httpClient != null) {
					httpClient.close();
				}
				if (response != null) {
					response.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;

	}
	
	/**
	 * 普通的post  json请求方式
	 * @param reqJson		请求的json
	 * @return
	 */
	public static String httpClientPost(String url, String reqJson) {
		String result = null;
		// 获得Http客户端
		CloseableHttpClient httpClient = HttpClientBuilder.create().build();

		// 创建Post请求
		HttpPost httpPost = new HttpPost(url);
		RequestConfig requestConfig = RequestConfig.
	        		custom().
	        		setConnectTimeout(6000).
	        		setConnectionRequestTimeout(6000).
	        		setSocketTimeout(6000).
	        		build();
		httpPost.setConfig(requestConfig);
		if(reqJson !=null){
			StringEntity entity = new StringEntity(reqJson, "UTF-8");
			// post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
			httpPost.setEntity(entity);
		}
		httpPost.setHeader("Content-Type", "application/json");

		// 响应模型
		CloseableHttpResponse response = null;
		try {
			// 由客户端执行(发送)Post请求
			response = httpClient.execute(httpPost);
			// 从响应模型中获取响应实体
			HttpEntity responseEntity = response.getEntity();

			logger.debug("响应状态为:" + response.getStatusLine());
			if (responseEntity != null) {
/*				System.out.println("响应内容长度为:" + responseEntity.getContentLength());
				System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));*/
				result =  EntityUtils.toString(responseEntity);
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				// 释放资源
				if (httpClient != null) {
					httpClient.close();
				}
				if (response != null) {
					response.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;

	}
	
	public static String httpClientPost(String url, String reqJson, String authToken,String clientId, String clientDevice) {
		String result = null;
		// 获得Http客户端
		CloseableHttpClient httpClient = HttpClientBuilder.create().build();

		// 创建Post请求
		HttpPost httpPost = new HttpPost(url);
		
		if(reqJson !=null){
			StringEntity entity = new StringEntity(reqJson, "UTF-8");
			// post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
			httpPost.setEntity(entity);
		}
		httpPost.setHeader("Content-Type", "application/json");
		httpPost.setHeader("X-AUTH-TOKEN", authToken);
		httpPost.setHeader("X-CLIENT-ID", clientId);
		httpPost.setHeader("X-CLIENT-DEVCODE", clientDevice);

		// 响应模型
		CloseableHttpResponse response = null;
		try {
			// 由客户端执行(发送)Post请求
			response = httpClient.execute(httpPost);
			// 从响应模型中获取响应实体
			HttpEntity responseEntity = response.getEntity();

			logger.debug("响应状态为:" + response.getStatusLine());
			if (responseEntity != null) {
/*				System.out.println("响应内容长度为:" + responseEntity.getContentLength());
				System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));*/
				result =  EntityUtils.toString(responseEntity);
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				// 释放资源
				if (httpClient != null) {
					httpClient.close();
				}
				if (response != null) {
					response.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;

	}
	
	/**
	 * form表单方式的请求
	 * @param map			文档中key=value的存储方式
	 * @param url			请求的url
	 * @return
	 * @throws Exception
	 */
	public static String formHttpClientPost(Map<String, String> map,String url) throws Exception{
		// 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
   
        // 创建http POST请求
        HttpPost httpPost = new HttpPost(url);
   
        // 设置post参数
        List<NameValuePair> parameters = new ArrayList<NameValuePair>(0);
        for(Map.Entry<String, String> entry : map.entrySet()){
            String mapKey = entry.getKey();
            String mapValue = entry.getValue();
            parameters.add(new BasicNameValuePair(mapKey, mapValue));
        }
        // 构造一个form表单式的实体
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters,"utf-8");
        // 将请求实体设置到httpPost对象中
        httpPost.setEntity(formEntity);
   
        httpPost.setHeader(
                "User-Agent",
                "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36");
   
        CloseableHttpResponse response = null;
        try {
            // 执行请求
            response = httpclient.execute(httpPost);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                String content = EntityUtils.toString(response.getEntity(),
                        "UTF-8");
                return content;
            }
        } finally {
            if (response != null) {
                response.close();
            }
            httpclient.close();
        }
        logger.debug("没有请求到");
        return null;
	}
	
	/**
	 * form表单的请求方式
	 * @param map
	 * @param url			文档中key=value的存储方式
	 * @param userNames		数组
	 * @return
	 * @throws Exception
	 */
	public static String formHttpClientPost(Map<String, String> map,String url,String[] userNames) throws Exception{
		// 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
   
        // 创建http POST请求
        HttpPost httpPost = new HttpPost(url);
   
        // 设置post参数
        List<NameValuePair> parameters = new ArrayList<NameValuePair>(0);
        for(Map.Entry<String, String> entry : map.entrySet()){
            String mapKey = entry.getKey();
            String mapValue = entry.getValue();
            parameters.add(new BasicNameValuePair(mapKey, mapValue));
        }
        //数组的组合方式，其中userNames为参数名
        for (int i = 0; i < userNames.length; i++) {
        	parameters.add(new BasicNameValuePair("userNames", userNames[i]));
		}
        
        // 构造一个form表单式的实体
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters,"utf-8");
        // 将请求实体设置到httpPost对象中
        httpPost.setEntity(formEntity);
   
        httpPost.setHeader(
                "User-Agent",
                "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36");
   
        CloseableHttpResponse response = null;
        try {
            // 执行请求
            response = httpclient.execute(httpPost);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                String content = EntityUtils.toString(response.getEntity(),
                        "UTF-8");
                return content;
            }
        } finally {
            if (response != null) {
                response.close();
            }
            httpclient.close();
        }
        logger.debug("没有请求到");
        return null;
	}
	
	public static String formHttpClientPost(Map<String, String> map,String url,String[] userNames,String[]years) throws Exception{
		// 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
   
        // 创建http POST请求
        HttpPost httpPost = new HttpPost(url);
   
        // 设置post参数
        List<NameValuePair> parameters = new ArrayList<NameValuePair>(0);
        for(Map.Entry<String, String> entry : map.entrySet()){
            String mapKey = entry.getKey();
            String mapValue = entry.getValue();
            parameters.add(new BasicNameValuePair(mapKey, mapValue));
        }
        for (int i = 0; i < userNames.length; i++) {
        	parameters.add(new BasicNameValuePair("userNames", userNames[i]));
		}
        for (int i = 0; i < years.length; i++) {
        	parameters.add(new BasicNameValuePair("years", years[i]));
		}
        
        // 构造一个form表单式的实体
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters,"utf-8");
        // 将请求实体设置到httpPost对象中
        httpPost.setEntity(formEntity);
   
        httpPost.setHeader(
                "User-Agent",
                "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36");
   
        CloseableHttpResponse response = null;
        try {
            // 执行请求
            response = httpclient.execute(httpPost);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                String content = EntityUtils.toString(response.getEntity(),
                        "UTF-8");
                return content;
            }
        } finally {
            if (response != null) {
                response.close();
            }
            httpclient.close();
        }
        logger.debug("没有请求到");
        return null;
	}
	

	public static String formHttpClientPost(Map<String, String> map,String url,String[] userNames,String[]authority,
			String[]apnData,String[]wifiData) throws Exception{
		// 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
   
        // 创建http POST请求
        HttpPost httpPost = new HttpPost(url);
   
        // 设置post参数
        List<NameValuePair> parameters = new ArrayList<NameValuePair>(0);
        for(Map.Entry<String, String> entry : map.entrySet()){
            String mapKey = entry.getKey();
            String mapValue = entry.getValue();
            parameters.add(new BasicNameValuePair(mapKey, mapValue));
        }
        for (int i = 0; i < userNames.length; i++) {
        	parameters.add(new BasicNameValuePair("userNames", userNames[i]));
		}
        if (authority != null) {
        	for (int i = 0; i < authority.length; i++) {
            	parameters.add(new BasicNameValuePair("authority", authority[i]));
    		}
		}
        
        if (apnData != null) {
        	for (int i = 0; i < apnData.length; i++) {
            	parameters.add(new BasicNameValuePair("apnData", apnData[i]));
    		}
		}
        if (wifiData != null) {
        	for (int i = 0; i < wifiData.length; i++) {
            	parameters.add(new BasicNameValuePair("wifiData", wifiData[i]));
    		}
		}
        
        
        // 构造一个form表单式的实体
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters,"utf-8");
        // 将请求实体设置到httpPost对象中
        httpPost.setEntity(formEntity);
   
        httpPost.setHeader(
                "User-Agent",
                "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36");
   
        CloseableHttpResponse response = null;
        try {
            // 执行请求
            response = httpclient.execute(httpPost);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                String content = EntityUtils.toString(response.getEntity(),
                        "UTF-8");
                return content;
            }
        } finally {
            if (response != null) {
                response.close();
            }
            httpclient.close();
        }
        logger.debug("没有请求到");
        return null;
	}
	
	public static String formHttpClientPostApanDatas(Map<String, String> map,String url,String[] apnDatas) throws Exception{
		// 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
   
        // 创建http POST请求
        HttpPost httpPost = new HttpPost(url);
   
        // 设置post参数
        List<NameValuePair> parameters = new ArrayList<NameValuePair>(0);
        for(Map.Entry<String, String> entry : map.entrySet()){
            String mapKey = entry.getKey();
            String mapValue = entry.getValue();
            parameters.add(new BasicNameValuePair(mapKey, mapValue));
        }
        for (int i = 0; i < apnDatas.length; i++) {
        	parameters.add(new BasicNameValuePair("apnDatas", apnDatas[i]));
		}
        
        // 构造一个form表单式的实体
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters,"utf-8");
        // 将请求实体设置到httpPost对象中
        httpPost.setEntity(formEntity);
   
        httpPost.setHeader(
                "User-Agent",
                "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36");
   
        CloseableHttpResponse response = null;
        try {
            // 执行请求
            response = httpclient.execute(httpPost);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                String content = EntityUtils.toString(response.getEntity(),
                        "UTF-8");
                return content;
            }
        } finally {
            if (response != null) {
                response.close();
            }
            httpclient.close();
        }
        logger.debug("没有请求到");
        return null;
	}
	
	public static String PostMultiData(String url,String filePath,String userName) throws Exception {
		CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpPost httppost = new HttpPost(url);

            File file = new File(filePath);
            FileBody bin = new FileBody(file);
            StringBody comment = new StringBody(userName, ContentType.TEXT_PLAIN);

            HttpEntity reqEntity = MultipartEntityBuilder.create()
                    .addPart("file", bin)
                    .addPart("userName", comment)
                    .build();


            httppost.setEntity(reqEntity);

            logger.debug("executing request " + httppost.getRequestLine());
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    System.out.println("Response content length: " + resEntity.getContentLength());
                    System.out.println(resEntity.getContent());
                    return EntityUtils.toString(resEntity,Charset.forName("UTF-8"));
                }
                EntityUtils.consume(resEntity);
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
        return null;
	}
	
	
}
